﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GoodStuff.Validation.Rules
{
    public class PropertyValidator<TEntity, TProperty> : IValidationRule<TEntity>
    {
        private Func<TEntity, TProperty> _propertyExpression;
        private IList<IValidationRule<TProperty>> _innerRules;

        public PropertyValidator(Func<TEntity, TProperty> propertyExpression, IValidationRule<TProperty> inner)
        {
            _propertyExpression = propertyExpression;
            _innerRules = new List<IValidationRule<TProperty>>() { inner };
        }

        public PropertyValidator(Func<TEntity, TProperty> propertyExpression, IList<IValidationRule<TProperty>> innerRules)
        {
            _propertyExpression = propertyExpression;
            _innerRules = innerRules;
        }

        public void Validate(TEntity target)
        {
            //retrieve the given property and delegate to clients.
            TProperty value = _propertyExpression(target);

            foreach (var rule in _innerRules)
            {
                rule.Validate(value);
            }
        }

        public bool IsValid
        {
            get { return _innerRules.All(p => p.IsValid); }
        }

        public string ErrorMessage
        {
            get { return string.Join("\n", _innerRules.Where(p => p.IsValid == false).Select(p => p.ErrorMessage).ToArray()); }
        }
    }
}
